// 在 CSS Modules 中，类名不会直接暴露给全局，而是会被编译成独一无二的类名（如 button_abc123），所以不能直接使用 "button" 作为 className。
import { useState } from 'react';
import login from './Login.module.scss'
import { login as loginApi } from '@/api/user';
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';

const Login = () => {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        username: '',
        password: ''
    });
    const [showPassword, setShowPassword] = useState(false);

    // 处理输入变化
    const handleInputChange = (e) => {
        const { id, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [id]: value
        }));
    };

    // 切换密码显示状态
    const togglePasswordVisibility = () => {
        setShowPassword(!showPassword);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        // 表单验证
        if (!formData.username || !formData.password) {
            message.error('请输入用户名和密码');
            return;
        }

        try {
            const res = await loginApi({
                username: formData.username,
                password: formData.password
            });

            console.log(res);

            if (res && res.data.token) {
                localStorage.setItem('token', res.data.token);
                message.success('登录成功！');
                navigate('/home');
            } else {
                message.error('登录失败：未获取到token');
            }
        } catch (error) {
            message.error(error.response.data.message);
            console.error('登录失败:', error);
        }
    }

    return (
        <>
            <div className={login.login}>
                <header className={login.login__header}>
                    <img src="/images/logo.svg" alt="logo" className={login.login__headerImg} />
                    <h1 className={login.login__headerTitle}>Finding Stations</h1>
                </header>

                <main className={login.login__main}>
                    <aside className={login.login__aside}>
                        <h2 className={login.login__asideTitle}>寻找遗失的美好~</h2>
                        <h3 className={login.login__asideSubtitle}>Looking for the lost beauty</h3>
                    </aside>

                    <form className={login.login__form} onSubmit={handleSubmit}>
                        <h3 className={login.login__formTitle}>管理员登录</h3>
                        <div className={login.login__formItem}>
                            <label htmlFor="username" className={login.login__formLabel}>用户名</label>
                            <input
                                type="text"
                                id="username"
                                className={login.login__formInput}
                                value={formData.username}
                                onChange={handleInputChange}
                                placeholder="请输入用户名"
                            />
                        </div>
                        <div className={login.login__formItem}>
                            <label htmlFor="password" className={login.login__formLabel}>密码</label>
                            <div className={login.login__formPassword}>
                                <input
                                    type={showPassword ? "text" : "password"}
                                    id="password"
                                    className={login.login__formInput}
                                    value={formData.password}
                                    onChange={handleInputChange}
                                    placeholder="请输入密码"
                                />
                                <span
                                    className={login.login__formPasswordIcon}
                                    onClick={togglePasswordVisibility}
                                >
                                    {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                </span>
                            </div>
                        </div>
                        <span className={login.login__formForget}>忘记密码？</span>
                        <button type="submit" className={login.login__formButton}>登录</button>
                    </form>
                </main>
            </div>
        </>
    )
}

export default Login